import * as vscode from "vscode";
import { getChineseList } from "./get-Chinese-list";

/**
 * 中文的标记，红框样式
 */
export function getChineseCharDecoration() {
  const color = "#f40";
  // TODO3：配置提示框样式
  return vscode.window.createTextEditorDecorationType({
    // borderWidth: "1px",
    // borderStyle: "dotted",
    // overviewRulerColor: color,
    // overviewRulerLane: vscode.OverviewRulerLane.Right,
    // light: {
    //   borderColor: color,
    // },
    // dark: {
    //   borderColor: color,
    // },
  });
}

let timeout: NodeJS.Timeout | null = null;
let prevChineseCharDecoration: vscode.TextEditorDecorationType | null = null;
export function triggerUpdateDecorations(callback?: any) {
  if (timeout) {
    clearTimeout(timeout);
  }
  timeout = setTimeout(() => {
    const activeEditor = vscode.window.activeTextEditor;
    if (prevChineseCharDecoration) {
      /** 清除原有的提示 */
      activeEditor?.setDecorations(prevChineseCharDecoration, []);
    }
    const { targetStrs, chineseCharDecoration } = updateDecorations() as any;
    prevChineseCharDecoration = chineseCharDecoration;
    callback(targetStrs);
  }, 500);
}

/**
 * 更新标记
 */
export function updateDecorations() {
  const activeEditor = vscode.window.activeTextEditor;
  const currentFilename = activeEditor?.document.fileName;
  const chineseCharDecoration = getChineseCharDecoration();
  if (!activeEditor) {
    return;
  }

  const text = activeEditor.document.getText();
  // 清空上一次的保存结果
  let targetStrs = [];
  let chineseChars: vscode.DecorationOptions[] = [];

  targetStrs = getChineseList(text, currentFilename as string);
  targetStrs.map((match) => {
    const hoverMessage = new vscode.MarkdownString(
      `[🐤 翻译中文文案🇨🇳：${
        match.text
      }](command:my-extension.translateText?${encodeURIComponent(
        JSON.stringify(match)
      )})`
    );
    hoverMessage.isTrusted = true;

    // TODO4：创建装饰对象
    // const decoration = {
    //   range: match.range,
    //   hoverMessage: hoverMessage,
    // };
    // chineseChars.push(decoration);
  });

  /** 设置中文的提示 */
  activeEditor.setDecorations(chineseCharDecoration, chineseChars);

  return {
    targetStrs,
    chineseCharDecoration,
  };
}
